/*
 * Duplicate Detector Copyright (C) 2010 Marco Biscaro <marcobiscaro2112@gmail.com>
 * 
 * This file is part of Duplicate Detector.
 *
 * Duplicate Detector is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Duplicate Detector is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Duplicate Detector.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.duplicatedetector.view;

import java.io.File;
import java.util.Map;
import java.util.Set;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;

import net.miginfocom.swing.MigLayout;

import com.googlecode.duplicatedetector.controller.ExpandNodesListener;
import com.googlecode.duplicatedetector.controller.FileDetailUpdater;
import com.googlecode.duplicatedetector.model.FileTreeModel;

/**
 * Panel used to show the search results.
 * 
 * @author Marco Biscaro
 */
public class ResultsPanel extends JPanel {

	private static final long serialVersionUID = 940460329741245588L;
	private Map<String, Set<File>> files;
	private transient FileTreeModel fileTreeModel;
	private JTree fileTree;
	private FileDetailsPanel fileDetailsPanel;

	public ResultsPanel(Map<String, Set<File>> files) {
		this.files = files;
		initialize();
	}

	private void initialize() {
		setLayout(new MigLayout("", "[grow]", "[grow]"));
		add(new JScrollPane(getFileTree()), "grow, w :400:, h :300:");
		add(new JScrollPane(getFileDetailsPanel()), "grow, w :400:, h :300:");
	}

	private JTree getFileTree() {
		if (fileTree == null) {
			fileTree = new JTree();
			fileTree.setModel(getFileTreeModel());
			for (int i = 0; i < fileTree.getRowCount(); i++) {
				fileTree.expandRow(i);
			}
			fileTree.setRootVisible(false);
			fileTree.setShowsRootHandles(true);
			fileTree.addTreeSelectionListener(new FileDetailUpdater(
					getFileDetailsPanel()));
		}
		return fileTree;
	}

	private FileTreeModel getFileTreeModel() {
		if (fileTreeModel == null) {
			fileTreeModel = new FileTreeModel(fileTree, files);
			fileTreeModel.addTreeModelListener(new ExpandNodesListener(
					getFileTree()));
		}
		return fileTreeModel;
	}

	private FileDetailsPanel getFileDetailsPanel() {
		if (fileDetailsPanel == null) {
			fileDetailsPanel = new FileDetailsPanel(getFileTreeModel());
		}
		return fileDetailsPanel;
	}

}
